package com.timous.web;

import com.timous.Entity.Comment;
import com.timous.Entity.User;
import com.timous.service.BlogService;
import com.timous.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class CommentController {

    @Value("${comment.avatar}")
    private String avatar;

    @Autowired
    private CommentService commentService;

    @Autowired
    private BlogService blogService;

    @GetMapping("/comments/{blogId}")
    public String commentList(@PathVariable Long blogId , Model model){

        model.addAttribute("comments" , commentService.listCommentByBlogId(blogId));


        return "blogdetails :: commentList";
    }

    @PostMapping("/comments")
    public String post(Comment comment , HttpSession session){

        Long blogid = comment.getBlog().getId();

        comment.setBlog(blogService.getBlog(blogid));

        User user = (User)session.getAttribute("user");

        if (user != null){

            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
            //comment.setNickname(user.getNickname());

        }else{
            comment.setAvatar(avatar);
        }

        commentService.savecomment(comment);

        return "redirect:/comments/"+comment.getBlog().getId();

    }



}
